﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using WCYCReader.Models;
using WCYCReader.Main.Core;
using WCYCReader.Main;
using System.Text;
using WCYCReader.Utility;
using System.Windows.Input;
using WCYCReader.ViewModels;

namespace WCYCReader.Pages
{
    public partial class SearchPage : PhoneApplicationPage
    {

        protected PerformanceProgressBar SearchProgressBar = new PerformanceProgressBar();

        protected SearchPageBookList_VM spbl_vm = new SearchPageBookList_VM();

        protected bool SearchLoading;

        protected int _nextPageNo = 1;

        protected int _pageSize = 10;

        protected string _total;

        protected string _searchName;

        protected bool _hasNext = true;

        protected string _base64String;

        protected ScrollBar scrollBar;

        protected bool TextBoxFocus;

        public SearchPage()
        {
            this.InitializeComponent();
        }

        protected void AddPerformanceProgressBar()
        {
            if (!this.SearchProgressBar.IsIndeterminate)
            {
                this.SearchProgressBar.IsIndeterminate = true;
                this.SearchProgressBar.Height = 20;
                this.SearchProgressBar.Foreground = new SolidColorBrush(Colors.Red);
            }
        }

        private void ContentGrid_Loaded(object sender, RoutedEventArgs e)
        {
            App.QQReader_prePageId = App.QQReader_pageId;
            App.QQReader_pageId = "QQReader_SearchPage";
            this.SearchBookListbox.ItemsSource = this.spbl_vm.T_SearchPageBookList_VM();
            if (!this.TextBoxFocus)
            {
                base.IsTabStop = true;
                this.TextBoxFocus = true;
                this.SearchName.Focus();
            }
            this.SetListScrollBarValueChanged();
            this.listGrid.Children.Add(this.SearchProgressBar);
        }

        private void ContentGrid_Unloaded(object sender, RoutedEventArgs e)
        {
            this.RemovePerformanceProgressBar();
            this.listGrid.Children.Remove(this.SearchProgressBar);
            this.scrollBar.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(this.verticalScrollBar_ValueChanged);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        protected void RemovePerformanceProgressBar()
        {
            if (this.SearchProgressBar.IsIndeterminate)
            {
                this.SearchProgressBar.IsIndeterminate = false;
            }
        }

        private void SearchBook_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        { 
            Deployment.Current.Dispatcher.BeginInvoke(()=>
            {
                if (e.Result == null)
                {
                    Prompt.PromptMessage("提示：网络异常！");
                }
                else
                {
                    JsonData blm = new JsonData();
                    blm = ParseJson.Parse<JsonData>(e.Result);
                    this._hasNext = blm.value.hasNext;
                    this._nextPageNo = blm.value.nextPageNo;
                    this._total = blm.value.total.ToString();
                    this.SearchNum.Text = ("搜索 “" + this.SearchName.Text + "” 共有 " + this._total.ToString() + " 个结果");
                    this.spbl_vm.SetSearchBookList(blm);
                }
                this.SearchLoading = false;
                this.RemovePerformanceProgressBar();
            });

        }

        private void SearchBook_HttpPostClient()
        {
            this.SearchLoading = true;
            this.AddPerformanceProgressBar();
            Dictionary<string, string> strs = new Dictionary<string, string>()
            {
                { "keyword", this._base64String },
                { "currenPage", this._nextPageNo.ToString() },
                { "pageSize", this._pageSize.ToString() },
                { "fromWho", "4" }
            };
            HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
            httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/search/keyword", UriKind.Absolute));
            //
            httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.SearchBook_DownloadStringCompleted);
        }

        private void SearchBook_OK()
        {
            if (!this.SearchLoading && this.SearchName.Text != "")
            {
                byte[] bytes = Encoding.UTF8.GetBytes(this.SearchName.Text);
                this._base64String = Convert.ToBase64String(bytes);
                this._hasNext = true;
                this._nextPageNo = 1;
                this.spbl_vm.RemoveSearchBookList();
                this.SearchBook_HttpPostClient();
            }
        }

        private void SearchBookListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0)
            {
                SettingHelper.SaveInToSettings("BookDetail", this.spbl_vm.T_SearchPageBookList_VM()[listBox.SelectedIndex]);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
            listBox.SelectedIndex = -1;
        }

        private void SearchName_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                base.Focus();
                this.SearchBook_OK();
            }
        }

        private void SearchName_LostFocus(object sender, RoutedEventArgs e)
        {
            this.SearchBook_OK();
        }

        private void SetListScrollBarValueChanged()
        {
            foreach (ScrollBar visualChildCollection in GetVisualChild.GetVisualChildCollection<ScrollBar>(this.SearchBookListbox))
            {
                if (visualChildCollection.Orientation != System.Windows.Controls.Orientation.Vertical)
                {
                    continue;
                }
                this.scrollBar = visualChildCollection;
                this.scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(this.verticalScrollBar_ValueChanged);
            }
        }

        private void verticalScrollBar_ValueChanged(object sender, RoutedEventArgs e)
        {
            ScrollBar scrollBar = (ScrollBar)sender;
            object value = scrollBar.GetValue(RangeBase.ValueProperty);
            object obj = scrollBar.GetValue(RangeBase.MaximumProperty);
            if (value != null && obj != null && (double)value + 0.3 > (double)obj && !this.SearchLoading && this._hasNext)
            {
                this.SearchBook_HttpPostClient();
            }
        }
    }
}